package com.hxh.myAop;

import com.hxh.entity.Project;
import com.hxh.service.*;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author HXH
 * @description: 记录项目版本变更，记录需要操作的类型，如重启、重新生成表代码、重新初始化项目
 */
@Aspect
@Component
@Slf4j
public class ProjectConfigRecordInitAspect {

    @Autowired
    private ProjectConfigRecordService projectConfigRecordService;


    /*************************重启标志处理 start********************************/
    /**
     * 拦截 GenerationSpringBootAdapter 中除 generationCRUDTools 外的所有方法
     */
    @AfterReturning("execution(public * com.hxh.generater.springBoot.GenerationSpringBootAdapter.*(..)) " +
            "&& !execution(* com.hxh.generater.springBoot.GenerationSpringBootAdapter.generationCRUDTools(..))")
    public void logAfterSpringBootMethod(JoinPoint joinPoint) {
        logMethodExecution(joinPoint, "back");
    }

    /**
     * 拦截 GenerationVueAdapter 的所有 public 方法
     */
    @AfterReturning("execution(public * com.hxh.generater.vue.GenerationVueAdapter.*(..))")
    public void logAfterVueMethod(JoinPoint joinPoint) {
        logMethodExecution(joinPoint, "front");
    }

    /**
     * 记录是否需要重启前端或者后端
     * GenerationVueAdapter类中，执行了方法，重启前端
     * GenerationSpringBootAdapter类中，执行了方法，重启后端
     */
    private void logMethodExecution(JoinPoint joinPoint, String module) {
        Object[] args = joinPoint.getArgs();
        String methodName = joinPoint.getSignature().getName();
        Object firstParam = args.length > 0 ? args[0] : null;
        if (firstParam instanceof Project) {
            Project project = (Project) firstParam;
            Integer id = project.getId();
            projectConfigRecordService.rebootSystem(id, module);
            if ("initProject".equals(methodName)) {
                projectConfigRecordService.clearInitFlag(id, module);
            }
        }
    }
    /*************************重启标志处理 end********************************/

}
